package com.csscaps.auth.controller;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.session.HttpServletSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.csscaps.auth.model.SysLog;
import com.csscaps.auth.model.SysUser;
import com.csscaps.auth.service.SysLogService;
import com.csscaps.auth.service.SysUserService;
import com.csscaps.system.shiro.ShiroUser;
import com.csscaps.system.utils.IPUtil;
import com.csscaps.system.utils.ResultUtil;
import com.csscaps.system.utils.UUIDGenerator;
@Controller
@RequestMapping(value = "/admin")
public class SysLoginController {

	private static final Logger LOG = Logger.getLogger(SysLoginController.class);

	@Autowired
	public SysUserService sysUserService;

	@Autowired
	private SysLogService sysLogService;
	@RequestMapping(value = "/doLogin" ,method=RequestMethod.POST)
	@ResponseBody
	public Map doLogin(@RequestParam(value = "account") String account,@RequestParam(value = "password") String password,HttpServletRequest request) {
		Map resoultMap = null;
		String pwd = null;
		Subject subject = SecurityUtils.getSubject();
		// 如果经过shiro的权限认证（session-认证）是通过用户，则不用做其他认证，直接放行
		SysUser user = sysUserService.selectByUserAcount(account);
		if (user != null) {
			pwd = Base64.decodeToString(user.getUserPassword());
		}
		if (null == user) {
			resoultMap = ResultUtil.getErrorResult("用户名不存在");
		}
		if ("0".equals(user.getUserEnable())) {
			resoultMap = ResultUtil.getErrorResult("用户禁用");
		}
		if (!pwd.equals(password)) {
			resoultMap = ResultUtil.getErrorResult("密码错误");
		} else {
	 
			
			
			UsernamePasswordToken token = new UsernamePasswordToken(account, password);
			token.setRememberMe(true);
			subject.login(token);
			Session session = SecurityUtils.getSubject().getSession();
			session.setAttribute("user", user);
			session.setAttribute(HttpServletSession.class.getName()+ ".HOST_SESSION_KEY" + ".HOST",IPUtil.getIpAddress(request));
			resoultMap = ResultUtil.getSuccessResult("登陆成功");
			SysLog log = new SysLog();
			log.setLogUuid(UUIDGenerator.genUuidStr());
			log.setLogCreateTime(new Date());
			log.setLogModule("用户管理");
			log.setLogFunction("用户登陆");
			log.setLogOperation("用户登陆");
			log.setLogDesc("登陆成功");
			log.setLogType("登陆日志");
			sysLogService.add(request, log);
		}
		return resoultMap;
	}

	@RequestMapping(value = "/logout",method=RequestMethod.GET)
	@ResponseBody
	public Map logout(HttpServletRequest request) {
		Map resoultMap = null;
		Subject subject = SecurityUtils.getSubject();
		try {
			if (subject != null) {
				subject.logout();
				SysLog log = new SysLog();
				log.setLogCreateTime(new Date());
				log.setLogUuid(UUIDGenerator.genUuidStr());
				log.setLogModule("用户管理");
				log.setLogFunction("用户退出");
				log.setLogOperation("用户退出");
				log.setLogDesc("退出成功");
				log.setLogType("登陆日志");
				sysLogService.add(request, log);
				resoultMap = ResultUtil.getSuccessResult("退出成功");
			} else {
				resoultMap = ResultUtil.getErrorResult("退出失败");
			}
		} catch (Exception e) {
			LOG.error(e.toString());
			resoultMap = ResultUtil.getErrorResult("退出失败");
		}
		return resoultMap;
	}

	@RequestMapping(value = "/getCurrentUser")
	@ResponseBody
	public Map getCurrentUser(HttpServletRequest request) {
		Map resoultMap = null;
		SysUser user = null;
		Subject subject = SecurityUtils.getSubject();
		try {
			if (subject != null) {
				  String userName = String.valueOf(((ShiroUser)subject.getPrincipal()).getUserAccount());
				user = sysUserService.selectByUserAcount(userName);
				resoultMap = ResultUtil.getSuccessResult(user);
			} else {
				resoultMap = ResultUtil.getErrorResult();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return resoultMap;
	}
}
